package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.bill.model.entity.WarehouseBill;
import com.wing.bill.model.entity.WarehouseProcessBill;
import com.wing.bill.service.WarehouseBillDetailService;
import com.wing.bill.service.WarehouseBillService;
import com.wing.bill.service.WarehouseProcessBillDetailService;
import com.wing.bill.service.WarehouseProcessBillService;
import com.wing.common.constant.SecurityConstants;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.dao.*;
import com.wing.product.model.entity.*;
import com.wing.product.model.response.WarehouseProductionOrderVO;
import com.wing.web.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

@Service
public class WarehouseProductionOrderServiceImpl extends ServiceImpl<WarehouseProductionOrderDao, WarehouseProductionOrder> implements WarehouseProductionOrderService {

    @Autowired
    WarehouseProductionOrderDetailDao warehouseProductionOrderDetailDao;
    @Autowired
    WarehouseProductionOrderDetailService warehouseProductionOrderDetailService;
    @Autowired
    WarehouseOutboundOrderDao warehouseOutboundOrderDao;
    @Autowired
    WarehouseOrderDao warehouseOrderDao;
    @Autowired
    WarehouseMaterialRequisitionRecordDao warehouseMaterialRequisitionRecordDao;
    @Autowired
    private WarehouseProcessBillService warehouseProcessBillService;
    @Autowired
    private WarehouseProcessBillDetailService warehouseProcessBillDetailService;

    @Autowired
    private WarehouseProcessingDescriptionDao warehouseProcessingDescriptionDao;

    @Autowired
    private WarehouseProductionOrderProcessingService warehouseProductionOrderProcessingService;


    @Override
    public Page<WarehouseProductionOrderVO> pageList4app(Page page, Map<String, Object> params) {
        List<WarehouseProductionOrderVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public WarehouseProductionOrderVO selectProductionDetail(Integer state,String id) {
        //查询生存订单
        WarehouseProductionOrderVO warehouseProductionOrderVO = this.baseMapper.selectProductionDetail(id);

        //查询生产记录明细
        LambdaQueryWrapper<WarehouseProductionOrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WarehouseProductionOrderDetail::getWarehouseProductionOrderId, warehouseProductionOrderVO.getId())
                .eq(WarehouseProductionOrderDetail::getIsDeleted, 0);
        if (ObjectUtil.isNotEmpty(state)){
            lambdaQueryWrapper.eq(WarehouseProductionOrderDetail::getState, state);
        }
        List<WarehouseProductionOrderDetail> warehouseProductionOrderDetailList = warehouseProductionOrderDetailDao.selectList(lambdaQueryWrapper);
        warehouseProductionOrderVO.setWarehouseProductionOrderDetailList(warehouseProductionOrderDetailList);
        warehouseProductionOrderVO.setWarehouseProcessingDescriptionList(warehouseProcessingDescriptionDao.findOrderProcessing(id));
        return warehouseProductionOrderVO;
    }

    @Override
    @Transactional
    public JsonResult saveWarehouseProductionOrder(WarehouseProductionOrderVO warehouseProductionOrderVO) {

            //添加生产订单
        if (ObjectUtil.isNotEmpty(warehouseProductionOrderVO)) {
            WarehouseProductionOrder warehouseProductionOrder = new WarehouseProductionOrder();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseProductionOrder.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseProductionOrderVO, warehouseProductionOrder, copyOptions);
            warehouseProductionOrder.setProductionOrderNumber(UniqueIdGeneratorUtil.generateUniqueId("SCDD", "yyyyMMddHHmmss", 1000, 9999));
            warehouseProductionOrder.setStatus("1");
            if (JwtUtils.getClientId().equals(SecurityConstants.WAREHOUSE_CLIENT_ID)) {
                warehouseProductionOrder.setSource("2");
            } else {
                warehouseProductionOrder.setSource("1");
            }
            this.baseMapper.insert(warehouseProductionOrder);

            //添加关联工艺信息
            try {
                if(warehouseProductionOrderVO.getWarehouseProductionOrderProcessingList().size()>0){
                    for (WarehouseProductionOrderProcessing warehouseProductionOrderProcessing :warehouseProductionOrderVO.getWarehouseProductionOrderProcessingList()) {
                        warehouseProductionOrderProcessing.setOrderId(warehouseProductionOrder.getId().toString());
                        warehouseProductionOrderProcessingService.save(warehouseProductionOrderProcessing);
                    }
                }
            }catch (Exception e
            ){
                e.printStackTrace();
            }

//            warehouseProductionOrderProcessingService.saveBatch(warehouseProductionOrderVO.getWarehouseProductionOrderProcessingList());

            //添加生产订单明细
            if (CollectionUtils.isNotEmpty(warehouseProductionOrderVO.getWarehouseProductionOrderDetailList())) {
                for (WarehouseProductionOrderDetail po : warehouseProductionOrderVO.getWarehouseProductionOrderDetailList()) {
                    po.setWarehouseProductionOrderId(warehouseProductionOrder.getId());
                    po.setScheduleQuantity(po.getRequiredQuantity());
                    po.setState(1);
                }
                warehouseProductionOrderDetailService.saveBatch(warehouseProductionOrderVO.getWarehouseProductionOrderDetailList());
            }

            //修改库存相关完成，需要 创建账单记录
            WarehouseProcessBill warehouseProcessBill = warehouseProcessBillService.isExistBill(warehouseProductionOrderVO.getCustomerId());
//         先判断 头部账单是否存在
            if(ObjectUtil.isEmpty(warehouseProcessBill)){
                //如果不存在 新增头部订单
                warehouseProcessBill = warehouseProcessBillService.createBill(warehouseProductionOrderVO.getCustomerId());
            }
//        生成新的账单
            warehouseProcessBillDetailService.addBillDetailOrder(warehouseProductionOrderVO.getCustomerId(),warehouseProcessBill.getId(),warehouseProductionOrderVO.getTotalProcessingFee().doubleValue(),warehouseProductionOrder.getId());

            return JsonResult.success("添加成功");
        } else {
            return JsonResult.fail("添加失败");
        }

    }

    @Override
    public JsonResult updateProduction(String id,String status){

        WarehouseProductionOrder warehouseProductionOrder = this.baseMapper.selectById(id);
        warehouseProductionOrder.setStatus(status);
        this.baseMapper.updateById(warehouseProductionOrder);
        return JsonResult.success("修改成功");
    }

    @Override
    @Transactional
    public JsonResult updateProductionOrder(WarehouseProductionOrderVO warehouseProductionOrderVO){

        WarehouseProductionOrder warehouseProductionOrder = new WarehouseProductionOrder();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WarehouseProductionOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseProductionOrderVO, warehouseProductionOrder, copyOptions);
        this.updateById(warehouseProductionOrder);

        LambdaQueryWrapper<WarehouseProductionOrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WarehouseProductionOrderDetail::getWarehouseProductionOrderId,warehouseProductionOrderVO.getId())
                .eq(WarehouseProductionOrderDetail::getIsDeleted,0);
        List<Long> warehouseProductionOrderDetailIds = warehouseProductionOrderDetailDao.selectList(lambdaQueryWrapper).stream().map(WarehouseProductionOrderDetail::getId).collect(Collectors.toList());
        warehouseProductionOrderDetailService.removeByIds(warehouseProductionOrderDetailIds);
        if (CollectionUtils.isNotEmpty(warehouseProductionOrderVO.getWarehouseProductionOrderDetailList())){
            for (WarehouseProductionOrderDetail po : warehouseProductionOrderVO.getWarehouseProductionOrderDetailList()){
                po.setWarehouseProductionOrderId(warehouseProductionOrder.getId());
            }
            warehouseProductionOrderDetailService.saveBatch(warehouseProductionOrderVO.getWarehouseProductionOrderDetailList());
        }
        return JsonResult.success("修改成功");
    }

    @Override
    public JsonResult<Map<Object, Object>> selectOrderTrend(){

        Map<Object,Object> orderMap = new HashMap<>();
        //生产订单
        LambdaQueryWrapper<WarehouseProductionOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WarehouseProductionOrder::getIsDeleted,0);
        List<WarehouseProductionOrder> warehouseProductionOrders = this.baseMapper.selectList(lambdaQueryWrapper);
        //出库订单
        LambdaQueryWrapper<WarehouseOutboundOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(WarehouseOutboundOrder::getIsDeleted,0);
        List<WarehouseOutboundOrder> warehouseOutboundOrders = warehouseOutboundOrderDao.selectList(orderLambdaQueryWrapper);
        //托管订单
        LambdaQueryWrapper< WarehouseOrder> warehouseOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        warehouseOrderLambdaQueryWrapper.eq(WarehouseOrder::getIsDeleted,0);
        List<WarehouseOrder> warehouseOrders = warehouseOrderDao.selectList(warehouseOrderLambdaQueryWrapper);

        LocalDate today = LocalDate.now();
        LocalDate sevenDaysAgo = today.minusDays(6);

        // 定义日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 使用年月日格式作为key
        Map<String, Long> dateCountMap = warehouseProductionOrders.stream()
                .filter(inventory -> !inventory.getCreateTime().toLocalDate().isBefore(sevenDaysAgo)
                        && !inventory.getCreateTime().toLocalDate().isAfter(today))
                .collect(Collectors.groupingBy(
                        inventory -> inventory.getCreateTime().format(formatter), // 将LocalDateTime格式化为年月日
                        TreeMap::new,
                        Collectors.counting()
                ));

        Map<String, Long> dateCountMapOut = warehouseOutboundOrders.stream()
                .filter(inventory -> !inventory.getCreateTime().toLocalDate().isBefore(sevenDaysAgo)
                        && !inventory.getCreateTime().toLocalDate().isAfter(today))
                .collect(Collectors.groupingBy(
                        inventory -> inventory.getCreateTime().format(formatter), // 将LocalDateTime格式化为年月日
                        TreeMap::new,
                        Collectors.counting()
                ));

        Map<String, Long> dateCountMapOreders = warehouseOrders.stream()
                .filter(inventory -> !inventory.getCreateTime().toLocalDate().isBefore(sevenDaysAgo)
                        && !inventory.getCreateTime().toLocalDate().isAfter(today))
                .collect(Collectors.groupingBy(
                        inventory -> inventory.getCreateTime().format(formatter), // 将LocalDateTime格式化为年月日
                        TreeMap::new,
                        Collectors.counting()
                ));
        // 填充缺失的日期，确保前七天都有值
        for (LocalDate date = sevenDaysAgo; !date.isAfter(today); date = date.plusDays(1)) {
            String formattedDate = date.format(formatter);
            dateCountMap.putIfAbsent(formattedDate, 0L);
            dateCountMapOut.putIfAbsent(formattedDate, 0L);
            dateCountMapOreders.putIfAbsent(formattedDate, 0L);
        }
        orderMap.put("production",dateCountMap);
        orderMap.put("out",dateCountMapOut);
        orderMap.put("order",dateCountMapOreders);

        return JsonResult.success(orderMap);
    }

    @Override
    public JsonResult<Map<Object, Object>> selectProductionOrderTrend(){

        Map<Object,Object> orderMap = new HashMap<>();
        //生产订单
        LambdaQueryWrapper<WarehouseProductionOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WarehouseProductionOrder::getIsDeleted,0)
                .orderByDesc(WarehouseProductionOrder::getProcessedQuantity);
        List<WarehouseProductionOrder> warehouseProductionOrders = this.baseMapper.selectList(lambdaQueryWrapper);
        List<Map> mapLis=baseMapper.orderRate();
        List<Map> mList=baseMapper.processingList();
        orderMap.put("productionList",mapLis);
        orderMap.put("processingList",mList);
//        orderMap.put("productionList",warehouseProductionOrders);

        LocalDate today = LocalDate.now();
        LocalDate sevenDaysAgo = today.minusDays(6);

        // 定义日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 使用年月日格式作为key
        Map<String, Long> dateCountMap = warehouseProductionOrders.stream()
                .filter(inventory -> !inventory.getCreateTime().toLocalDate().isBefore(sevenDaysAgo)
                        && !inventory.getCreateTime().toLocalDate().isAfter(today))
                .collect(Collectors.groupingBy(
                        inventory -> inventory.getCreateTime().format(formatter), // 将LocalDateTime格式化为年月日
                        TreeMap::new,
                        Collectors.counting()
                ));
        // 填充缺失的日期，确保前七天都有值
        for (LocalDate date = sevenDaysAgo; !date.isAfter(today); date = date.plusDays(1)) {
            String formattedDate = date.format(formatter);
            dateCountMap.putIfAbsent(formattedDate, 0L);

        }

        //安全生产天数
        LambdaQueryWrapper<WarehouseMaterialRequisitionRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarehouseMaterialRequisitionRecord::getIsDeleted,0)
                .orderByAsc(WarehouseMaterialRequisitionRecord::getCreateTime);
        List<WarehouseMaterialRequisitionRecord> warehouseMaterialRequisitionRecords = warehouseMaterialRequisitionRecordDao.selectList(queryWrapper);
        if (com.alibaba.nacos.common.utils.CollectionUtils.isNotEmpty(warehouseMaterialRequisitionRecords)){
            // 获取第一条数据的创建时间
            LocalDateTime createTime = warehouseMaterialRequisitionRecords.get(0).getCreateTime();

            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 计算时间差值
            Duration duration = Duration.between(createTime, now);
            long daysDifference = duration.toDays();       // 差值（天）
            orderMap.put("safeDays",daysDifference);
        }
        orderMap.put("productionMap",dateCountMap);

        return JsonResult.success(orderMap);
    }
}
